﻿using System.Collections.Generic;
using System.Data.SqlClient;

namespace TechMadeira.Core.Command
{
    public delegate void ChangeHandler( ICommandManager aManager );
    public class CommandManager : ICommandManager
    {
        #region Singleton usage: CommandManager.Instance

        private static readonly CommandManager mInstance = new CommandManager();


        static CommandManager()
        {
        }

        private CommandManager()
        {
        }

        public static CommandManager Instance {
            get { return mInstance; } 
        }

        #endregion 

        #region Fields
        private List<ICommand> mCommands = new List<ICommand>();
        private int mPosition = -1;
        #endregion

        public event ChangeHandler OnChange;

        public void Execute( ICommand aCommand )
        {
            if ( HasRedo() )
            {
                for ( int i = mCommands.Count - 1 ; i > mPosition ; i-- )
                    mCommands[i].Abort();
                mCommands.RemoveRange( 
                    mPosition + 1, mCommands.Count - mPosition - 1 );
            }
            aCommand.Execute();
            mCommands.Add( aCommand );
            mPosition = mCommands.Count - 1;

            if ( OnChange != null ) OnChange( this );
        }

        public void Undo()
        {
            if ( ! HasUndo() ) return;
            mCommands[mPosition--].Undo();
            if ( OnChange != null ) OnChange( this );
        }

        public void Redo()
        {
            if ( ! HasRedo() ) return;
            mCommands[++mPosition].Redo();
            if ( OnChange != null ) OnChange( this );
        }

        public bool HasUndo()
        {
            return ( mPosition > -1 );
        }

        public bool HasRedo()
        {
            return ( mPosition < mCommands.Count - 1 );
        }
    }
}
